package com.gitee.huanminabc.dynamicdb.core;

import com.gitee.huanminabc.dynamicdb.common.DynamicDbException;
import com.gitee.huanminabc.dynamicdb.common.SpringContextHolder;
import com.gitee.huanminabc.dynamicdb.config.DynamicDbSpringConfig;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.DependsOn;

/**
 * @program: java-huanmin-utils
 * @description: 多租户
 * @author: huanmin
 * @create: 2024-12-09 14:11
 **/
@DependsOn("DbSpringContextHolder")
public class TenantKey implements ApplicationContextAware {

    private static DynamicDbSpringConfig dynamicDbSpringConfig;

    public static   String getKeyDb(String key){
        //如果不是多租户模式那么直接返回就可以了
        if (!dynamicDbSpringConfig.isMultiTenantMode()){
            return key;
        }
        String tenant = DBContext.tenantKeys.get();
        if (tenant == null) {//如果现在没有租户那么就跳过使用默认的
           return key;
        }
        String dbKey = dynamicDbSpringConfig.getTenantDb(tenant, key);
        //获取数据源key
        if (dbKey == null) {
            throw new DynamicDbException("tenant:{},key:{} 租户数据源不存在", tenant, key);
        }
        return dbKey;
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        dynamicDbSpringConfig =(DynamicDbSpringConfig) SpringContextHolder.getBean(DynamicDbSpringConfig.class);
        if ( dynamicDbSpringConfig.isMultiTenantMode()) {
            if (dynamicDbSpringConfig.getTenants() == null || dynamicDbSpringConfig.getTenants().isEmpty()) {
                throw new DynamicDbException("多租户模式下,租户配置不能为空");
            }
        }
    }
}
